import java.io.File
import javax.xml.parsers.DocumentBuilderFactory
import net.crazyadam.{Constant, Path, Earth, Point}

/**
 *
 * @author joseph
 * @since 6/17/12 12:25 PM
 */

import math._

object Main {
  val multiTrack = "gx:MultiTrack"
  val track = "gx:Track"
  //單條路線track的tag
  val coordinate = "gx:coord"
  //座標tag
  val db = DocumentBuilderFactory.newInstance.newDocumentBuilder


  def main(args: Array[String]) {
    for (file <- new File(Constant.dataFolder).listFiles() if file.getName.endsWith(Constant.kmlSuffix)) {
      //只解析後綴爲Constant.kmlSuffix的KML文件
      println(file.getAbsolutePath)
      val e = new Earth
      val path = new Path
      var coordinatesList: List[Point] = List[Point]()
      try {
        val dom = db.parse(file)
        val list = dom.getElementsByTagName(coordinate) //讀取座標信息
        for (i <- 1 to list.getLength) {
          val c = parse(list.item(i - 1).getTextContent) //解析後得到三維數組
          c.name = i + "號"
          coordinatesList ::= c
        }
        var previous: Point = null
        var prePrevious: Point = null

        val coordinates = coordinatesList.reverse.map(p => {
          //因爲最後添加的數據放在list的head裏，所以需要reverse調整排序
          if (null != previous) {
            //求出和W->E向的夾角,將此點與上一點的夾角存在此點
            p.theta = e.theta(previous, p)
            //求與當前點間隔一個點的倆點之夾角
            if (null != prePrevious)
              p.preTheta = e.theta(prePrevious, p)
          } else
            e.setOrigin(p) //求地球半經時，需要當前緯度
          prePrevious = previous
          previous = p
          p //map 返回值
        })
        coordinates.reverse.foreach(p => path.addPoint(p))
      } catch {
        case e: Exception => e.printStackTrace()
      }
      path.mergeSections //如此便
      for (p <- path.path) {
        println("分段" + p)
        println("distance:" + p.length(e) + "-->" + toDegrees(p.averageTheta))
      }

    }
  }

  def parse(string: String): Point = {
    //"\\s+"用於匹配任意個空位字符串
    val c = string.trim.split("\\s+").map(s => s.toDouble)
    require(c.length == 3)
    new Point(c(0), c(1), c(2))
  }

}
